package com.wusiwei.controller;

import com.wusiwei.common.Result;
import com.wusiwei.service.OrderService;
import com.wusiwei.service.ReceiptService;
import com.wusiwei.vo.ReceiptStatistics;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 统计数据控制器
 */
@RestController
@RequestMapping("/api/statistics")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "统计数据", description = "系统各模块统计数据API接口")
public class StatisticsController {

    private final OrderService orderService;
    private final ReceiptService receiptService;

    /**
     * 获取订单统计数据
     */
    @GetMapping("/orders")
    @Operation(summary = "获取订单统计", description = "获取订单相关统计数据")
    public Result<Map<String, Object>> getOrderStatistics(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate
    ) {
        try {
            log.info("获取订单统计数据，参数：startDate={}, endDate={}", startDate, endDate);

            Map<String, Object> statistics = new HashMap<>();

            // 获取订单按状态统计
            List<Map<String, Object>> statusStats = orderService.countByStatus();
            statistics.put("statusStats", statusStats);

            // 获取订单按供应商统计
            List<Map<String, Object>> supplierStats = orderService.countBySupplier();
            statistics.put("supplierStats", supplierStats);

            // 获取订单总金额信息
            Map<String, Object> amountStats = orderService.getTotalAmountStats();
            statistics.put("totalAmount", amountStats.get("totalAmount"));
            statistics.put("currentMonthAmount", amountStats.get("currentMonthAmount"));
            statistics.put("averageAmount", amountStats.get("averageAmount"));
            statistics.put("monthGrowthRate", amountStats.get("monthGrowthRate"));

            // 获取订单总数
            int totalCount = orderService.countTotal();
            statistics.put("totalCount", totalCount);

            // 获取当月订单数
            int currentMonthCount = orderService.getCurrentMonthOrderCount();
            statistics.put("currentMonthCount", currentMonthCount);

            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取订单统计数据失败", e);
            return Result.error("获取订单统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单月度趋势数据
     */
    @GetMapping("/orders/monthly")
    @Operation(summary = "获取订单月度趋势", description = "获取指定年份的订单月度趋势数据")
    public Result<List<Map<String, Object>>> getOrderMonthlyTrend(
            @Parameter(description = "年份，默认为当年") @RequestParam(required = false) Integer year
    ) {
        try {
            if (year == null) {
                year = Calendar.getInstance().get(Calendar.YEAR);
                log.info("未指定年份，使用当前年份: {}", year);
            } else {
                log.info("获取订单月度趋势数据，请求参数year={}", year);
            }

            // 检查指定年份是否有订单数据，仅用于日志记录
            try {
                int orderCount = orderService.countOrdersByYear(year);
                log.info("{}年的订单数量: {}", year, orderCount);
            } catch (Exception e) {
                log.warn("统计{}年订单数量出错: {}", year, e.getMessage());
            }

            // 获取订单月度趋势
            List<Map<String, Object>> trendData = orderService.getMonthlyOrderTrend(year);

            // 确保有返回值，即使是空列表
            if (trendData == null) {
                log.warn("订单月度趋势数据为null，返回空列表");
                trendData = new ArrayList<>();
            }

            // 记录结果数据
            if (!trendData.isEmpty()) {
                log.info("成功获取月度趋势数据，共返回{}条记录", trendData.size());
                // 记录第一条和最后一条数据作为示例，便于调试
                if (trendData.size() > 0) {
                    log.info("第一条记录: {}", trendData.get(0));
                    log.info("最后一条记录: {}", trendData.get(trendData.size() - 1));
                }
            } else {
                log.warn("月度趋势数据为空");
            }

            return Result.success(trendData);
        } catch (Exception e) {
            log.error("获取订单月度趋势数据失败", e);
            return Result.error("获取订单月度趋势数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取收货单统计数据
     */
    @GetMapping("/receipts")
    @Operation(summary = "获取收货单统计", description = "获取收货单相关统计数据")
    public Result<Map<String, Object>> getReceiptStatistics(
            @Parameter(description = "年份，默认为当年") @RequestParam(required = false) Integer year
    ) {
        try {
            // 如果未指定年份，使用当前年份
            if (year == null) {
                year = Calendar.getInstance().get(Calendar.YEAR);
                log.info("未指定年份，使用当前年份: {}", year);
            } else {
                log.info("获取收货单统计数据，请求参数year={}", year);
            }

            Map<String, Object> statistics = new HashMap<>();

            // 获取收货单状态统计
            ReceiptStatistics receiptStats = receiptService.getReceiptStatusStatistics();

            if (receiptStats != null) {
                // 基本统计数据
                statistics.put("totalCount", receiptStats.getTotalCount());
                statistics.put("pendingCount", receiptStats.getPendingCount());
                statistics.put("acceptedCount", receiptStats.getAcceptedCount());
                statistics.put("totalAmount", receiptStats.getTotalAmount());

                // 计算验收率
                int totalCount = receiptStats.getTotalCount();
                int acceptedCount = receiptStats.getAcceptedCount();
                double acceptanceRate = totalCount > 0 ? ((double) acceptedCount / totalCount) * 100 : 0;
                statistics.put("acceptanceRate", Math.round(acceptanceRate));

                // 构建状态统计数据，用于饼图
                List<Map<String, Object>> statusStats = new ArrayList<>();

                Map<String, Object> pendingMap = new HashMap<>();
                pendingMap.put("status", "待验收");
                pendingMap.put("count", receiptStats.getPendingCount());
                statusStats.add(pendingMap);

                Map<String, Object> acceptedMap = new HashMap<>();
                acceptedMap.put("status", "已验收");
                acceptedMap.put("count", receiptStats.getAcceptedCount());
                statusStats.add(acceptedMap);

                statistics.put("statusStats", statusStats);
            }

            // 获取当月数据
            int currentMonthCount = receiptService.getCurrentMonthReceiptCount();
            BigDecimal currentMonthAmount = receiptService.getCurrentMonthReceiptAmount();
            statistics.put("currentMonthCount", currentMonthCount);
            statistics.put("currentMonthAmount", currentMonthAmount);

            // 获取月度趋势数据
            List<Map<String, Object>> monthlyTrend = receiptService.getMonthlyReceiptTrend(year);
            statistics.put("monthlyTrend", monthlyTrend);

            // 获取供应商TOP5数据
            List<Map<String, Object>> supplierTop5 = receiptService.getReceiptStatsBySupplier(5);
            statistics.put("supplierTop5", supplierTop5);

            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取收货单统计数据失败", e);
            return Result.error("获取收货单统计数据失败: " + e.getMessage());
        }
    }
} 